package me.duzhi.blog.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import io.jpress.core.JBaseController;
import io.jpress.model.Comment;
import io.jpress.model.Content;
import io.jpress.model.User;
import io.jpress.model.query.CommentQuery;
import io.jpress.model.query.ContentQuery;
import io.jpress.model.query.OptionQuery;
import io.jpress.model.query.UserQuery;
import io.jpress.router.RouterMapping;
import io.jpress.utils.EncryptUtils;
import io.jpress.utils.HttpUtils;
import io.jpress.utils.StringUtils;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ashang.peng@aliyun.com
 * @date 二月 01, 2017
 */
@RouterMapping(url = "/dtools", viewPath = "/templates/duzhi/")
public class DuoshuoController extends JBaseController {
    public static String url;
    public static String short_name;
    public static String secret;

    static {
        url = OptionQuery.me().findValue("duzhi_duoshuo_json");
        short_name = OptionQuery.me().findValue("duzhi_duoshuo_shortName");
        secret = OptionQuery.me().findValue("duzhi_duoshuo_secret");

    }

    public void index() {

    }

    public void commmentsSync() throws Exception {
        Map map = new HashMap<>();
        map.put("short_name", short_name);
        map.put("secret", secret);
        JSONObject jsonObject = JSON.parseObject(HttpUtils.get(url, map));

        JSONArray commentArray = jsonObject.getJSONArray("response");
        for (int i = 0; i < commentArray.size(); i++) {
            JSONObject object = commentArray.getJSONObject(i);
            BigInteger comment_id = object.getBigInteger("post_id");
            if (CommentQuery.me().findById(comment_id) == null) {
                createComment(object);
            }
        }
        renderAjaxResult("ok",0);
    }

    private void createComment(JSONObject object) {
        if ("create".equals(object.getString("action"))) {
            JSONObject meta = object.getJSONObject("meta");
            String thread_key = meta.getString("thread_key");

            boolean tx = Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
                    Content content = null;
                    if (thread_key != null && thread_key.startsWith("s.duzhi.me_url_")) {
                        content = ContentQuery.me().findById(new BigInteger(thread_key.substring("s.duzhi.me_url_".length())));
                    }
                    if (content == null) {
                        return false;
                    }
                    Comment comment1 = CommentQuery.me().findById(meta.getBigInteger("post_id"));
                    if(comment1!=null){
                        return false;
                    }
                    String email = meta.getString("author_email");
                    String author_id = meta.getString("author_id");
                    User user = null;
                    if(StringUtils.isBlank(email)){
                        email = author_id+"@duzhi.me";
                    }
                    if (StringUtils.isNotBlank(email)) {
                         user = UserQuery.me().findUserByEmail(email);
                        if(user==null){
                            user = new User();
                            String author_name = meta.getString("author_name");
                            user.setNickname(author_name);
                            user.setUsername("author_name"+String.valueOf(new Date().getTime()));
                            user.setEmail(email);
                            String salt = EncryptUtils.salt();
                            user.setSalt(salt);
                            user.setCreated(new Date());
                            String password = "password1323";
                            if (StringUtils.isNotEmpty(password)) {
                                password = EncryptUtils.encryptPassword(password, salt);
                                user.setPassword(password);
                            }
                            user.saveOrUpdate();
                          //  user.save();
                        }
                    }
                    Comment comment = new Comment();
                    comment.setId(meta.getBigInteger("post_id"));
                    comment.setContentModule(content.getModule());
                    comment.setType(Comment.TYPE_COMMENT);
                    comment.setContentId(content.getId());
                    String text = meta.getString("message");
                    comment.setText(text);
                    comment.setUserId(user.getId());
                    comment.setIp(meta.getString("ip"));
                    comment.setAgent(meta.getString("agent"));
                    comment.setAuthor(meta.getString("author_name"));
                    comment.setEmail(email);
                    comment.setType(Comment.TYPE_COMMENT);
                    comment.setStatus(Comment.STATUS_NORMAL);
//            comment.setUserId(userId);
                    comment.setCreated(meta.getDate("created_at"));
                    comment.setParentId(meta.getBigInteger("parent_id"));
                    comment.save();
                    return true;
                }
            });

        }

    }
}
